<template>
	<layout>
		<view class="h-fill content">
			<u-navbar title="达人后台" :background="navBg" :borderBottom="false" titleColor="#fff" backIconColor="#fff"></u-navbar>
			<!-- #ifdef MP-WEIXIN -->
			<official-account></official-account>
			<!-- #endif -->
			<view class="header">
				<image class="h-fill" src="../static/img/img_beijing_dianpu@2x.png" mode="widthFix"></image>
				<view class="header-content" :style="{top: headerTop + 'px'}">
					<view class="uni-flex align-center pad">
						<image class="user-head" :src="userInfo.avatar || '/static/img/user.png'"></image>
						<view class="l-mg uni-flex uni-column">
							<view class="uni-flex align-center">
								<text class="uni-bold uni-text-big r-mg-2">{{userInfo.nickname || '未设置'}}</text>
								<nice-grade :showCrown="userInfo.shareGrade > 0" v-if="userInfo.shareGrade !== undefined" :level="userInfo.shareGrade"
								 leftText="LV" :rightText="expertGrades[userInfo.shareGrade + ''].label"></nice-grade>
							</view>
							<text>ID: {{userInfo.id || '-'}}&nbsp;&nbsp;&nbsp;({{realShareManId ? '分享ID：' + realShareManId : ''}})</text>
						</view>
					</view>
					<view class="pad" style="color: #000000">
						<view class="simple-card round-corner uni-flex align-center" style="height: 221rpx;">
							<uni-grid @change="handleGridChange" :column="3" :square="false" :showBorder="false" class="h-fill">
								<uni-grid-item :index="0">
									<view class="uni-flex-extend uni-flex uni-column align-center">
										<text class="uni-bold uni-text-big">{{(((userInfo.teamTotalIncome + userInfo.personalTotalIncome) || 0) / 100).toFixed(2)}}</text>
										<text class="uni-text-gray">总收益</text>
									</view>
								</uni-grid-item>
								<uni-grid-item :index="1">
									<view class="uni-flex-extend uni-flex uni-column align-center">
										<text class="uni-bold uni-text-big">{{((userInfo.account.balance || 0) / 100).toFixed(2)}}</text>
										<text class="uni-text-gray">可用资产</text>
									</view>
								</uni-grid-item>
								<uni-grid-item :index="2">
									<view class="uni-flex-extend uni-flex uni-column align-center">
										<text class="uni-bold uni-text-big">{{userInfo.teamCount || '0'}}</text>
										<text class="uni-text-gray">团队人数</text>
									</view>
								</uni-grid-item>
							</uni-grid>
						</view>
					</view>
					<image class="banner r-mg l-mg" src="../static/img/dianpu_banner.png" mode="widthFix"></image>
					<view class="l-pad r-pad t-pad">
						<view class="simple-card round-corner">
							<uni-list>
								<uni-list-item @click="navTo('./my-team')" thumb="/pagesUser/static/img/ic_tuandui@2x.png" title="我的团队"></uni-list-item>
								<uni-list-item @click="navTo('../../pagesFoo/order/order')" thumb="/pagesUser/static/img/order.png" title="我的订单"></uni-list-item>
								<uni-list-item @click="navTo('./my-account')" thumb="/pagesUser/static/img/ic_shouji@2x.png" title="我的收益"></uni-list-item>
								<uni-list-item @click="navTo('./orders')" thumb="/pagesUser/static/img/ic_dingdan_jilu@2x.png" title="收益记录"></uni-list-item>
							</uni-list>
						</view>
						<view class="simple-card round-corner t-mg b-mg">
							<uni-list>
								<uni-list-item @click="handleMyCode" thumb="/pagesUser/static/img/ic_dian_erwei@2x.png" title="推广二维码"></uni-list-item>
								<uni-list-item @click="navTo('./guidance')" thumb="/pagesUser/static/img/ic_jiaocheng@2x.png" title="教程中心"></uni-list-item>
								<!-- <uni-list-item @click="handleScan" thumb="/pagesUser/static/img/ic_jiaocheng@2x.png" title="扫一扫"></uni-list-item> -->
								<!-- <uni-list-item @click="navTo('../settings')" thumb="/pagesUser/static/img/ic_jiaocheng@2x.png" title="设置"></uni-list-item> -->
							</uni-list>
						</view>
					</view>
				</view>
			</view>
			<popup-wx-public v-model="wxPublicVisible" :params="currentCity"></popup-wx-public>
		</view>
		<u-popup v-if="posters" v-model="popupPosterVisible" mode="bottom" border-radius="20" :closeable="true">
			<view class="bg-white">
				<view class="uni-center pad-base" style="font-size: 34rpx;">长按图片可转发</view>
				<!-- <u-swiper :list="posters" :current="posterIdx" @change="posterChange" :autoplay="false" :effect3d="true" height="800"
				 img-mode="aspectFit" bg-color="transparent" :effect3d-previous-margin="80"></u-swiper> -->
				<swiper style="height: 800rpx;" next-margin="80rpx" previous-margin="80rpx" :indicator-dots="true" indicator-active-color="#D61719">
					<swiper-item v-for="(item, idx) in posters" :key="idx">
						<u-lazy-load v-if="item.posterUrl" :image="item.posterUrl" height="800" imgMode="aspectFit"></u-lazy-load>
						<image src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/easy-loadimage/loading.gif" class="h-fill v-fill" mode="aspectFit"></image>
					</swiper-item>
				</swiper>
				<share-expert-poster v-if="currentPoster" ref="poster" :templateUrl="currentPoster.templateUrl" :qrcodeUrl="qrcodeImgUrl" @completed="handlePosterCompleted"></share-expert-poster>
				<!-- <view class="pad-t-base">
					<scroll-view scroll-x>
						<view class="pad-l-base">
							<image v-for="(item, idx) in posters" :key="idx" :src="item"
								class="mg-r-base"
								style="height: 215rpx;width: 142rpx;vertical-align: bottom;"></image>
						</view>
					</scroll-view>
				</view> -->
				<view class="pad-base">
					<u-button @click="handleSave" type="primary" shape="circle" hover-class="none" :custom-style="{'background-color': '#D61719', height: '88rpx'}">
						<view class="h-box">
							<image src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/ic_fenxiang_anniu@2x.png" class="img-40 mg-r-xs"></image>
							保存图片
						</view>
					</u-button>
				</view>
			</view>
		</u-popup>
		<u-modal v-model="modalOpenSetting" cancel-text="取消" :show-cancel-button="true" :show-title="false" content="请先打开保存到相册开关">
			<view slot="confirm-button" class="h-box justify-center v-fill">
				<u-button @click="modalOpenSetting = false" open-type="openSetting" :custom-style="{color: 'transparent'}" hover-class="none">
					<view class="text-dark">去设置</view>
				</u-button>
			</view>
		</u-modal>
	</layout>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from "vuex"
	// #ifndef MP
	import {
		getNavHeight
	} from "../../common/maUtil.js"
	// #endif
	// #ifdef MP
	import {
		getNavHeightMp as getNavHeight
	} from "../../common/maUtil.js"
	// #endif
	import {
		getUserInfo,
		getPosterList,
		getMyShareCode,
		getNeareastCity
	} from "../../api/platform/user.js"
	import {
		expertGrades
	} from "../../common/constants.js"
	
	export default {
		data() {
			return {
				expertGrades,
				navBg: {
					'background-image': 'linear-gradient(to right, #434AD8, #8E77F5)'
				},
				headerTop: 0,
				wxPublicVisible: false,
				popupPosterVisible: false,
				posters: null,
				posterIdx: 0,
				shareCode: {},
				
				modalOpenSetting: false,
				
				currentPoster: null,
				posterComplete: true,
				currentCity: undefined
			}
		},
		computed: {
			...mapState(['userInfo']),
			realShareManId() {
				if (this.userInfo.shareGrade > 0) {
					return this.userInfo.id
				} else if (this.shareManId) {
					return this.shareManId
				} else {
					return this.userInfo.id
				}
			},
			qrcodeImgUrl() {
				if (this.shareCode._id) {
					let text = encodeURIComponent(`https://test.the3dspace.cn/register-share-expert?codeId=${this.shareCode._id}@&codeCity=${this.currentCity.codeCity}&nameCity=${this.currentCity.nameCity}`)
					return `${this.$cloudUrl}/genQRCode?text=${text}`
				}
			}
		},
		created() {
			this.headerTop = getNavHeight() + 30;
		},
		onReady() {
			this.loadData();
			// let notRemind = uni.getStorageSync("notRemind");
			// if (!notRemind) {
			// 	this.$refs.popup.open();
			// }
		},
		async onPullDownRefresh() {
			await this.loadData();
			uni.stopPullDownRefresh();
		},
		methods: {
			...mapMutations(["updateUserInfo"]),
			handlePosterCompleted(path) {
				var fileName = path.substring(path.lastIndexOf('/') + 1)
				if (!fileName.endsWith('.jpg')) {
					fileName = fileName + '.jpg'
				}
				this.posterComplete = true
				uni.showLoading({
					mask: true
				})
				console.log("cloudPath: ",`poster/${fileName}`);
				uniCloud.uploadFile({
					filePath: path,
					cloudPath: `poster/${fileName}`,
					success: async (res) => {
						try{
							let count = await this.$dbHelper.getCount("file-cache", {
								where: `srcUrl == 'poster_${this.userInfo._id}_${this.currentPoster.templateId}_${ this.currentCity.codeCity }.jpg'`
							})
							if (!count) {
								await this.$dbHelper.insert("file-cache", {
									showLoading: false,
									data: {
										fileID: res.fileID,
										srcUrl: `poster_${this.userInfo._id}_${this.currentPoster.templateId}_${ this.currentCity.codeCity }.jpg`
									}
								})
							}
							this.currentPoster.posterUrl = `${this.$cloudUrl}/getTecentImgUrl?fileID=${res.fileID}&_t=Date.now()`
							uni.hideLoading()
						}catch(e){
							console.error(e)
							uni.hideLoading()
						}
					},
					fail: (err) => {
						this.$showError(err)
						uni.hideLoading()
					}
				})
			},
			handleScan() {
				// #ifndef H5
				uni.scanCode({
					scanType: "qrcode",
					complete: (res) => {
						this.$log("扫码结果", res);
						if (!res.result) {
							//用户取消了扫码
							return;
						}
						const reg = /register-share-expert\?codeId=\w{1,}@/
						const reg1 = /&codeCity=\d{4}/
						const reg2 = /&nameCity=(.+)/
						console.log(res.result);
						if (reg.test(res.result)) {
							let t = reg.exec(res.result)[0];
							let codeId = t.replace("register-share-expert\?codeId=", '').replace('@', '');
							let codeCity = reg1.exec(res.result)[0].substr(10, 4)
							let nameCity = reg2.exec(res.result)[0].substr(10)
							uni.navigateTo({
								url: `./register-share-expert?codeId=${codeId}&codeCity=${codeCity}&nameCity=${nameCity}`
							})
						} else {
							uni.showModal({
								title: "不支持的二维码类型",
								showCancel: false,
							})
						}
					}
				})
				// #endif
			},
			posterChange(idx) {
				this.posterIdx = idx
				if (!this.posters[idx].posterUrl && this.posterComplete) {
					this.currentPoster = this.posters[idx]
					this.posterComplete = false
					this.$refs.poster.draw()
				}
			},
			doSave() {
				if (!this.posters[this.posterIdx].posterUrl) {
					return
				}
				uni.showLoading({
					mask: true
				})
				uni.getImageInfo({
					src: this.posters[this.posterIdx].posterUrl,
					success: (res) => {
						uni.saveImageToPhotosAlbum({
							filePath: res.path,
							success: (res1) => {
								uni.hideLoading()
								this.$toast("保存成功")
							},
							fail: (err) => {
								console.error(err)
								uni.hideLoading()
							}
						})
					},
					fail: (err) => {
						console.error(err)
						uni.hideLoading()
					}
				})
			},
			handleSave() {
				// #ifdef MP-WEIXIN
				// this.$refs.poster[this.posterIdx].saveImage()
				uni.getSetting({
					success: (res) => {
						if (res.authSetting['scope.writePhotosAlbum'] === true) {
							this.doSave()
						} else if (res.authSetting['scope.writePhotosAlbum'] === false) {
							this.modalOpenSetting = true
						} else {
							uni.authorize({
								scope: 'scope.writePhotosAlbum',
								success: () => {
									this.doSave()
								},
								fail: (err) => {
									console.error(err)
								}
							})
						}
					}
				})
				// #endif
			},
			handleMyCode() {
				if (!this.userInfo.shareGrade) {
					uni.showModal({
						title: "提示",
						content: "普通用户没有推广权限，请先联系客服升级为达人！客服微信：i3d008",
						cancelText: "知道了",
						confirmText: "复制微信",
						success: (res) => {
							if (res.confirm) {
								// #ifdef MP-WEIXIN
								uni.setClipboardData({
									data: "i3d008",
									success: () => {
										uni.showModal({
											title: "提示",
											content: "客服微信已复制，请去微信添加",
											confirmText: "知道了",
											showCancel: false
										})
									}
								})
								// #endif
							}
						}
					})
					return;
				}
				this.showPosterPopup()
			},
			async showPosterPopup() {
				uni.showLoading({
					mask: true
				})
				try {
					if (!this.posters) {
						this.posters = await getPosterList({}, this.currentCity.codeCity)
						this.shareCode = await getMyShareCode({
							showLoading: false
						})
						for (let i = 0; i < this.posters.length; i++) {
							if (!this.posters[i].posterUrl) {
								this.currentPoster = this.posters[i]
								this.$nextTick(() => {
									this.$refs.poster.draw()
								})
							}
						}
					}
					this.popupPosterVisible = true
					uni.hideLoading()
				} catch (e) {
					uni.hideLoading()
					console.error(e)
				}
			},
			handleGridChange(e) {
				switch (e.detail.index) {
					case 0:
						this.navTo("./orders");
						break;
					case 1:
						this.navTo("./my-account");
						break;
					case 2:
						this.navTo("./my-team");
						break;
				}
			},
			navTo(url) {
				uni.navigateTo({
					url: url
				})
			},
			async loadData() {
				try {
					this.posters = null
					
					let [err, loc] = await uni.getLocation({
					  type: "gcj02"
					})
					if (err) {
            loc = uni.getStorageSync('userLocation')
          }
          this.userLocation = {
            latitude: loc.latitude,
            longitude: loc.longitude
          }
					let localRegion = uni.getStorageSync("currentRegion")
					if (!localRegion) {
						let region = await getNeareastCity({
							showLoading: false,
							userLocation: this.userLocation
						})
						this.currentCity = {
							codeCity: region.city.value,
							nameCity: region.name
						}
						uni.setStorageSync("currentRegion", region)
					} else {
						this.currentCity = {
							codeCity: localRegion.city.value,
							nameCity: localRegion.name
						}
					}
					let userInfo = await getUserInfo({}, this.currentCity.codeCity)
					this.updateUserInfo(userInfo)
					this.wxPublicVisible = !userInfo.isWxPubUser
				} catch (e) {
					this.$log("加载主页数据遇到错误", e);
				}
			}
		}
	}
</script>

<style lang="scss">
	.header {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;

		&-content {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			color: #FFFFFF;
		}
	}

	.banner {
		width: 710rpx;
		vertical-align: middle;
	}

	.popup {
		width: 600rpx;
	}

	.img-qrcode {
		width: 300rpx;
		height: 300rpx;
	}
</style>
